<?php
namespace app\home\controller;

// 公共控制器
use app\common\controller\Home AS HomeController;
use PDO;
use think\Cookie;

// 用户中心的控制器
class User extends HomeController{
    public function __construct()
    {
        parent::__construct();

        // 地区模型
        $this->RegionModel=model('Region');
        $this->UserModel=model('User.User');
        $this->PostModel=model('Post.post');
        $this->CommentModel=model('Post.Comment');
        $this->RecordModel=model('User.Record');
    }

    // 用户中心 点击头像跳转到该头像的用户主页
    public function index(){
        //判断是否有传递userid
        $userid = $this->request->param('userid', 0);

        //查询这个用户是否存在
        $user = $this->UserModel->find($userid);

        if($user)
        {
            $postlist=$this->PostModel->where(['userid'=>$userid])->order('createtime','desc')->limit(12)->select();
            $commentlist=$this->CommentModel->with(['user','post'])->where(['comment.userid'=>$userid])->order('createtime','desc')->limit(5)->select();

            $this->assign([
                'user'=>$user,
                'postlist'=>$postlist,
                'commentlist'=>$commentlist,
            ]);
            
            //如果找到了 就说明要查看用户
            //看别人的时候，我给另外一个模板
            return $this->fetch('user');
        }else
        {
            $postlist=$this->PostModel->where(['userid'=>$this->LoginUser['id']])->order('createtime','desc')->limit(12)->select();
            $commentlist=$this->CommentModel->with(['user','post'])->where(['comment.userid'=>$this->LoginUser['id']])->order('createtime','desc')->limit(5)->select();

            // var_dump(collection($postlist)->toArray());
            // exit;
            //没找到，说明就是看自己本人的会员中心
            //渲染模板
            $this->assign([
                'postlist'=>$postlist,
                'commentlist'=>$commentlist,
            ]);

            return $this->fetch();
        }
    }

    // 基本设置
    public function profile(){
        if($this->request->isPost()){
            $action=$this->request->param('action','');

            // 获取全部数据
            $params=$this->request->param();

            // 我的资料
            if($action=="profile"){
                // 组装数据
                $data=[
                    'id'=>$this->LoginUser['id'],
                    'email'=>$params['email'],
                    'nickname'=>$params['nickname'],
                    'sex'=>$params['sex'],
                    'province'=>$params['province'],
                    'city'=>$params['city'],
                    'district'=>$params['district'],
                    'content'=>$params['content'],
                ];

                // 判断是否有改邮箱，如果改了邮箱需要重新认证
                if($params['email'] != $this->LoginUser['email']){
                    $data['auth']=0;
                }

                // common/User/User验证器 profile场景
                $result=$this->UserModel->validate('common/User/User.profile')->isUpdate(true)->save($data);

                if($result===FALSE){
                    $this->error($this->UserModel->getError());
                    exit;
                }else{
                    // 设置一个保存cookie信息
                    $data=[
                        'id'=>$this->LoginUser['id'],
                        'nickname'=>$params['nickname'],
                        'vip'=>$this->LoginUser['vip'],
                        'auth'=>$this->LoginUser['auth'],
                        'avatar'=>is_file($this->LoginUser['avatar']) ? '/'.$this->LoginUser['avatar'] : '/assets/home/images/avatar.jpg',
                        'cover'=>is_file($this->LoginUser['cover']) ? '/'.$this->LoginUser['cover'] : '/assets/home/images/back.jpg'
                    ];

                    if($params['email'] != $this->LoginUser['email']){
                        $data['auth']=0;
                    }

                    // 将用户信息设置到cookie里
                    Cookie::set('LoginUser',$data);
                    $this->success('更新个人资料成功');
                    exit;
                }
            }

            // 修改密码
            if($action=='password'){
                // 当前密码
                $nowpass=$this->request->param('nowpass','');
                $password=$this->request->param('password','');
                $repass=$this->request->param('repass','');

                // 密码盐
                $salt=$this->LoginUser['salt'];

                // 加密
                $nowpass=md5(trim($nowpass).$salt);

                if($nowpass != $this->LoginUser['password']){
                    $this->error('当前密码输入错误');
                    exit;
                }

                // 判断是否等于原来的密码
                $nowpass=md5(trim($password).$salt);
                if($nowpass==$this->LoginUser['password']){
                    $this->error('新密码不能和当前密码相同');
                    exit;
                }

                // 判断密码和确认密码是否一致
                if($password != $repass){
                    $this->error('密码和确认密码不一致');
                    exit;
                }

                // 重新生成密码盐
                $salt=randstr(10);

                // 新密码加密
                $password=md5(trim($password).$salt);

                // 组装数据
                $data=[
                    'id'=>$this->LoginUser['id'],
                    'salt'=>$salt,
                    'password'=>$password
                ];

                // 调用模型的更新方法
                $result=$this->UserModel->isUpdate(true)->save($data);

                if($result===FALSE){
                    $this->error($this->UserModel->getError());
                    exit;
                }else{
                    $this->success('密码修改成功');
                    exit;
                }
            }

            // 头像修改
            if($action=='avatar'){
                $result=upload('avatar');

                if($result===FALSE){
                    $this->error('头像修改失败');
                    exit;
                }

                // 组装数据
                $data=[
                    'id'=>$this->LoginUser['id'],
                    'avatar'=>'uploads/'.$result
                ];

                // 更新数据库
                $success=$this->UserModel->isUpdate(true)->save($data);

                if($success===FALSE){
                    // 上传上来的图片要删除
                    @is_file($data['avatar']) && @unlink($data['avatar']);

                    $this->error('修改头像失败');
                    exit;
                }else{
                    // 修改成功后，将原来的图片删除
                    $avatar=ltrim($this->LoginUser['avatar'],"/");
                    @is_file($avatar) && @unlink($avatar);
                    
                    // 重新更新cookie的信息
                    $cookie=[
                        'id'=>$this->LoginUser['id'],
                        'nickname'=>$this->LoginUser['nickname'],
                        'vip'=>$this->LoginUser['vip'],
                        'auth'=>$this->LoginUser['auth'],
                        'avatar'=>is_file($data['avatar']) ? '/'.$data['avatar'] : '/assets/home/images/avatar.jpg',
                        'cover'=>is_file($this->LoginUser['cover']) ? $this->LoginUser['cover'] : '/assets/home/images/back.jpg',
                    ];

                    // 将用户信息设置到cookie里面
                    Cookie::set('LoginUser',$cookie);

                    $this->success('修改头像成功',url('home/user/profile'));
                    exit;
                }
            }

            // 封面修改
            if($action=='cover'){
                $result=upload('cover');

                if($result===FALSE){
                    $this->error('封面修改失败');
                    exit;
                }

                // 组装数据
                $data=[
                    'id'=>$this->LoginUser['id'],
                    'cover'=>'uploads/'.$result
                ];

                // 更新数据库
                $success=$this->UserModel->isUpdate(true)->save($data);

                if($success===FALSE){
                    // 上传上来的图片要删除
                    @is_file($data['cover']) && @unlink($data['cover']);

                    $this->error('修改封面失败');
                    exit;
                }else{
                    // 修改成功后，将原来的图片删除
                    $cover=ltrim($this->LoginUser['cover'],"/");
                    @is_file($cover) && @unlink($cover);
                    
                    // 重新更新cookie的信息
                    $cookie=[
                        'id'=>$this->LoginUser['id'],
                        'nickname'=>$this->LoginUser['nickname'],
                        'vip'=>$this->LoginUser['vip'],
                        'auth'=>$this->LoginUser['auth'],
                        'avatar'=>is_file($this->LoginUser['avatar']) ? '/'.$this->LoginUser['avatar'] : '/assets/home/images/avatar.jpg',
                        'cover'=>is_file($data['cover']) ? '/'.$data['cover'] : '/assets/home/images/back.jpg',
                    ];

                    // 将用户信息设置到cookie里面
                    Cookie::set('LoginUser',$cookie);

                    $this->success('修改封面成功',url('home/user/profile'));
                    exit;
                }
            }
        }

        // 查询地区表的省份数据
        $province=$this->RegionModel->where(['grade'=>1])->select();

        // 判断当前这个用户是否有选择省份
        if(empty($this->LoginUser['province'])){
            $city=[];
        }else{
            $city=$this->RegionModel->where(['parentid'=>$this->LoginUser['province']])->select();
        }

        // 判断当前用户是否选择城市
        if(empty($this->LoginUser['city'])){
            $district=[];
        }else{
            $district=$this->RegionModel->where(['parentid'=>$this->LoginUser['city']])->select();
        }
        
        // 赋值
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('district',$district);

        return $this->fetch();
    }

    // 查询地区的
    public function area(){
        if($this->request->isPost()){
            // 获取的地区码
            $code=$this->request->param('code',0);

            // 根据地区码查询城市、区域
            $arealist=$this->RegionModel->where(['parentid'=>$code])->select();

            // 返回json数据
            return json($arealist);
        }
    }

    // 发送邮箱
    public function email(){
        if($this->request->isPost()){
            // 将邮箱进行md5加密
            $email=md5($this->LoginUser['email']);

            // 组装信息
            $msg="<a href='http://www.ask.com/home/index/email?email=$email'>点击免费邮箱验证</a>";

            // 调用公用函数库里面邮箱发送方法
            $result=send($this->LoginUser['email'],$msg);

            $success=[
                'result'=>false,
                'msg'=>''
            ];

            if($result){
                $success['result']=true;
                $success['msg']='发送邮件成功，请注意查收';
            }else{
                $success['result']=false;
                $success['msg']='邮件发送失败，请重新发送';
            }

            return json($success);
        }
    }

    // 我的消费记录
    public function record(){
        $recordlist=$this->RecordModel->with('user')->where(['userid'=>$this->LoginUser['id']])->order('createtime','desc')->paginate(10);

        $pagestr=$recordlist->render();
        
        $this->assign([
            'recordlist'=>$recordlist,
            'pagestr'=>$pagestr,
        ]);

        return $this->fetch();
    }
}

?>